text:
Q: Automate process of Disk Cleanup cleanmgr.exe without user intervention I am developing a powershell script file which shall execute some disk cleanup without user intervention. The user shall not be able to configure anything.
When I run cleanmgr.exe /d c: sageset:1 a popup window appears to select files/folders to be cleaned(cleanup options).
This will create a registry entry containing the settings with the cleanup options and after this, you can run cleanmgr.exe /sagerun:1 which will actually execute the cleanup.
Is there a way to specify the cleanup options directly with powerhell/command line(without the need to manually select things to be deleted)?

A: The PowerShell logic provided below is dynamic and ready for use or automation with the sageset options all being selected and no user interaction being required. This was inspired by multiple answers and comments from this post.
Note: I've adjusted for my needs and used successfully without any issues on multiple remote and local Windows 10 systems in particular.
Run on Local System
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\*' | % {
    New-ItemProperty -Path $_.PSPath -Name StateFlags0001 -Value 2 -PropertyType DWord -Force
   };
Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:1' ##-WindowStyle Hidden

Run on Remote System
$cred = Get-Credential "domain\administrator";
Invoke-Command -ComputerName "computer004" {
    Process {
        Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\*' | % {
            New-ItemProperty -Path $_.PSPath -Name StateFlags0001 -Value 2 -PropertyType DWord -Force
           };
        Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:1' -WindowStyle Hidden
    }
} -AsJob -Credential $cred

Supporting Resources

*

*cleanmgr

*Invoke-Command

-AsJob
   Run the command as a background job on a remote computer.
   Use this parameter to run commands that take an extensive time to complete.

*Get-Credential

*Automate process of Disk Cleanup cleanmgr.exe without user intervention

*Creating a Disk Cleanup Handler

A: You can use cleanmgr /verylowdisk to silently automate all the cleanup steps.

A: The only solution I found is to manually set the registry values like this:
...
#Set StateFlags0012 setting for each item in Windows 8.1 disk cleanup utility
if (-not (get-itemproperty -path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Active Setup Temp Folders' -name StateFlags0012 -ErrorAction SilentlyContinue)) {
set-itemproperty -path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Active Setup Temp Folders' -name StateFlags0012 -type DWORD -Value 2
set-itemproperty -path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\BranchCache' -name StateFlags0012 -type DWORD -Value 2
set-itemproperty -path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Downloaded Program Files' -name StateFlags0012 -type DWORD -Value 2

...
see full example

A: I ran into the same issue.  Researching the possible ways, I have found the following:
http://stealthpuppy.com/cleaning-up-and-reducing-the-size-of-your-master-image/
It shows how to create the sageset registry settings via cmd.  You can then use the sagerun:# cmd.  I have not tried it via script yet, but have validated that it works...

A: The following Powershell script automates CleanMgr.exe. In this case, it removes temporary files and runs the Update Cleanup extension to purge superseded Service Pack Backup files (Windows 10 now does this automatically via a scheduled task). To automate other extensions, create a "StateFlags0001" property in the corresponding Registry key, as done in the New-ItemProperty lines. You will find the Registry key names in the "VolumeCaches" branch.
As far as being silent, this script attempts to start CleanMgr.exe in a hidden window. However, at some point CleanMgr spawns new processes which are visible and must be waited on separately.
Write-Host 'Clearing CleanMgr.exe automation settings.'
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\*' -Name StateFlags0001 -ErrorAction SilentlyContinue | Remove-ItemProperty -Name StateFlags0001 -ErrorAction SilentlyContinue

Write-Host 'Enabling Update Cleanup. This is done automatically in Windows 10 via a scheduled task.'
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Update Cleanup' -Name StateFlags0001 -Value 2 -PropertyType DWord

Write-Host 'Enabling Temporary Files Cleanup.'
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Temporary Files' -Name StateFlags0001 -Value 2 -PropertyType DWord

Write-Host 'Starting CleanMgr.exe...'
Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:1' -WindowStyle Hidden -Wait

Write-Host 'Waiting for CleanMgr and DismHost processes. Second wait neccesary as CleanMgr.exe spins off separate processes.'
Get-Process -Name cleanmgr,dismhost -ErrorAction SilentlyContinue | Wait-Process

$UpdateCleanupSuccessful = $false
if (Test-Path $env:SystemRoot\Logs\CBS\DeepClean.log) {
    $UpdateCleanupSuccessful = Select-String -Path $env:SystemRoot\Logs\CBS\DeepClean.log -Pattern 'Total size of superseded packages:' -Quiet
}

if ($UpdateCleanupSuccessful) {
    Write-Host 'Rebooting to complete CleanMgr.exe Update Cleanup....'
    SHUTDOWN.EXE /r /f /t 0 /c 'Rebooting to complete CleanMgr.exe Update Cleanup....'
}

A: This script will get all the Volume Caches from the Registry, enable them to be cleaned and run the CLEANMGR.EXE for all caches.
$VolumeCachesRegDir = "hklm:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
$CacheDirItemNames = Get-ItemProperty "$VolumeCachesRegDir\*" | select -ExpandProperty PSChildName

$CacheDirItemNames |
    %{
        $exists = Get-ItemProperty -Path "$VolumeCachesRegDir\$_" -Name "StateFlags6553" -ErrorAction SilentlyContinue
        If (($exists -ne $null) -and ($exists.Length -ne 0))
            {
                Set-ItemProperty -Path "$VolumeCachesRegDir\$_" -Name StateFlags6553 -Value 2
            }
        else
            {
                New-ItemProperty -Path "$VolumeCachesRegDir\$_" -Name StateFlags6553 -Value 0 -PropertyType DWord
            }
     }
Start-Sleep -Seconds 3

Write-Host 'Running CleanMgr.exe...'
Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:65535' -WindowStyle Hidden -PassThru
cls

A: Running CleanMgr.exe in a powershell script or by itself seems to work fine as long as you run it locally with an account that has local admin rights. But try running it remotely via any remote management tool or remote scripting command (Invoke-Command) and it does not run. You might see the process running on the remote system but it doesn't seem to cleanup anything and the process never ends. I would be interested if anyone has been able to get cleanmgr.exe to run remotely without any user interaction. E.G. ConfigMgr Right Click Tools, ConfigMgr App or PKG, Task Scheduler.


text:
Q: Improving Machine learning model for trading and trend prediction I am working on making predictions and decisions based on stocks and crypto data.
First I implemented a decision tree model and I had Model Accuracy: 0.5. After that I did some research and found out that decision tree is not enough and I tried to improve it with random forest and adaboosting.
After that I noticed that I have 3 above mentioned algorithms with the same training and test data, and I get three different results.
Now the question is if it is possible to make the three algorithms work together by combining them in some way and benefit from the previous result?

A: You can combine classifiers, yes. This is considered an ensemble. It's a bit weird to make an ensemble from a decision tree and a random forest, though. A random forest  is an ensemble of decision trees. That's why it's called a forest.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proteger páginas que são carregadas dentro do template - Kohana Estou fazendo um admin aqui que carrega no miolo as respectivas páginas. Sei como permitir que sejam acessadas somente após o login, mas não sei se da maneira que estou fazendo é o modo correto. Vejam o Template:
class Controller_Administracao extends Controller_Template {
        //put your code here
        public $template = 'template_admin';

        public function before() {
            parent::before();
            if($this->auto_render){
                $this->template->content = '';
            }
        }
        public function after() {
            parent::after();

        }
    }

Até ai tudo bem, aqui eu chamo a action e faço a "proteção" dela:
public function action_home(){
            //Aqui uso o Auth do Kohana, está tudo normal
            //Se não estiver feito o login, volta para a tela inicial
            $user = Auth::instance()->get_user();
            if(!$user){
                $this->redirect('/');
            }
            //Feito o login, vai para o Dashboard
            else{
                $this->template->content = View::factory('admin/default');
            }
        }

A minha dúvida é: Eu preciso verificar com o Auth::instance()->get_user() em todas as actions que vão ser chamadas dentro do template ou tem alguma forma de proteger todas as actions sem precisar ficar fazendo essa verificação? Existe a possibilidade de fazer isso no próprio template?

A: Já tive contato muito superficial com o Kohana, não conheço os detalhes, mas de forma genérica baseado no modelo MVC, posso fazer algumas considerações que podem ajudar.

Existe a possibilidade de fazer isso no próprio template

Se você tem um sistema que possui login, quando o usuário for acessar - alterar seus dados, o controller validará a sessão e vai decidir a ação que será executada.
1 . Quando o user estiver conectado e acessar o perfil, serão exibidos os dados pessoais.
2 . Caso a sessão não seja validada, o controller vai capturar e executar um redirecionamento para a tela de login ou simplesmente carregar o formulário de login.
Veja que isso é uma responsabilidade exclusiva do controller. Manter qualquer tipo de controle de acesso ou validação de dados na view é um erro.

A minha dúvida é: Eu preciso verificar com o Auth::instance()->get_user() em todas as actions que vão ser chamadas dentro do template ou tem alguma forma de proteger todas as actions sem precisar ficar fazendo essa verificação?

Se todos os métodos do seu Controller_Administracao precisam ser validados, você deve usar o método before que será executado ANTES do método invocado.
public function before() {
     parent::before();

     // template definido
     $this->template->content = View::factory('admin/default');

     // usuário não identificado - executa o redirecionamento
     if( ! $user ){
        $this->redirect('/');
     }
}

Note que não vou entrar nos detalhes próprios do Kohana por não conhecer tão bem, mas o método before é o que você precisa para não repetir a mesma verificação de autenticidade em todos os outros métodos do seu controller.


text:
Q: Angular2 image upload with Rest I have Rest API
I use ng2-file-upload like this
My backend recieves following data
 {"file"=>"#<ActionDispatch::Http....bla bla.."}

When i am using rails front end - its ok. I need fix angular2. My backend is waiting data like this:
"photo"=>{"title"=>"qwerty", "image"=> "#<ActionDispatch::Http...blabla..."}

I change
      this.alias = uploader.options.itemAlias || 'file';

to
this.alias = uploader.options.itemAlias || 'image';

But I don't no how append 'photo'=> before form.
I deployed simple backend on heroku https://backend-file-upload.herokuapp.com/photos
Github apibackend - this
Angular2 deployed - this
. If this problem be fix, I will be start to create my project. Please help.)))

A: I suggest you take a look at ng2-file-upload.
Just tweak uploader settings and you should be good to go
uploader:FileUploader = new FileUploader({url: URL});

Documentation is a bit incomplete, so take a look at the demo.


text:
Q: Transfer learning using saved bottleneck values (inference with full model) I'm using lastest Keras with tensorflow backend.
I'm not quite sure the correct way to put together the full model for inference, if I used a smaller version of my model for training on bottleneck values.
# Save  bottleneck values

from keras.applications.xception import Xception
base_model = Xception(weights='imagenet', include_top=False)
prediction =  base_model.predict(x)
** SAVE bottleneck data***

Now  let's say my full model looks something like this:
base_model = Xception(weights='imagenet', include_top=False)
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(classes, activation='softmax')(x)
model = Model(input=base_model.input, output=predictions)

but to speed up training, I wanted to bypass the earlier layers by loading bottleneck values; so I create a smaller model (including only the new layers). I then train and save the model.
bottleneck_input = Input(shape = bottleneck_shape)
x = GlobalAveragePooling2D() (bottleneck_input)
x = Dense(1024, activation='relu')(x)
predictions = Dense(classes, activation='softmax')(x)
model = Model(input= bottleneck_input, output=predictions)
save_full_model() #save model

after training this smaller model, I want to run inference on the full model. So I need to put together the base model and the smaller model. Not sure what is the best way to to do this.
base_model = Xception(weights='imagenet', include_top=False)
#x = base_model.output

loaded_model = load_model() # load bottleneck model

#now to combine both models (something like this?)
Model(inputs = base_model.inputs, outputs = loaded_model.outputs)

What is the proper way to put together the model for inference?
I don't know if there is a way to use my full-model for training, and just start from the bottleneck layers for training and input layer for inference.  (Please not this is not the same as freeze layers, which just freezes the weights (weights won't be updated), but still calculates each data point.)

A: Every model is a layer with extra properties such as loss function etc. So you can use them like a layer in the functional API. In your case it could look like:

input = Input(...)
base_model = Xception(weights='imagenet', include_top=False)
# Apply model to input like layer
base_output = base_model(input)
loaded_model = load_model()
# Now the bottleneck model
out = loaded_model(base_output)
final_model = Model(input, out) # New computation graph


text:
Q: How to get back column value if df.ColumnName, where Columnname is comes from user in Pyspark My code is below in Pyspark:
Product = results.where(results.ColumnName == ProductName )
Product.show()

Where i want ColumnName should come from User like:
ColumnName = input("enter column name")

but I get the error as below:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-64-3e0600c86491> in <module>()
----> 1 Prediction_Product_Wise = results.where(results.ColumnName == ProductName ).select(
ColumnName,'probability','prediction').orderBy("probability",ascending=False)
  2 Prediction_Product_Wise.show()

/usr/local/lib/python3.6/dist-packages/pyspark/sql/dataframe.py in __getattr__(self, name)
 1399         if name not in self.columns:
 1400             raise AttributeError(
 -> 1401                 "'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
 1402         jc = self._jdf.apply(name)
 1403         return Column(jc)

 AttributeError: 'DataFrame' object has no attribute 'ColumnName'

Basically I wanted to check whether Product column has that value in it or not.
For example
Product
apple
ball
cat

and the data frame is df then df.Product == apple should return True value.
And I want to give user that at place of Product column he/she can choose any column name according to preference.

A: Assuming ColumnName is a string, you can do this.
from pyspark.sql.functions import col

Product = results.where(col(ColumnName) === ProductName)
Product.show()

A: You can try creating a function like this to do your task. This will return False for columns which are not there in the dataframe.
def is_value(df, column_name: str, value):
    if column_name in df.columns:
        return bool(df.where(df[column_name] == value).first())
    return False


text:
Q: Notation to assign a statement or predicate to a symbol If I want the statement "$4>2$" be represented by the letter $p$, how should it be written?
$$p:4>2\\
p= 4>2\\
p \equiv "4>2"$$
On the other hand, if I have two predicates $A(x)$ and $B(x)$, and I want to represent the conjunction of both predicates using the symbol $C(x),$ how should it be written?
$$C(x) = A(x) \wedge B(x)\\
C(x) \equiv A(x) \wedge B(x)$$

A: All these are unambiguous:

*

*Let $P$ represent the formula $4>2.$

*We use $C(x)$ to denote the formula $A(x) \wedge B(x).$

*$P\overset {\;\mathsf {def}}{\iff} 4>2$

*$C(x)\overset {\;\mathsf {def}}{\iff} A(x) \wedge B(x)$
Although = normally connects logic terms rather than logic formulae, these too are unambiguous:

*

*$P:=4>2$

*$C(x):= A(x) \wedge B(x)$
Don't write this, as it suggests that the LHS and RHS are logically equivalent by derivation instead of by definition:

$$C(x) \equiv A(x) \wedge B(x).$$

A: Hint: It might be convenient to consider the usage of Iverson brackets
\begin{align*}
[P]=
\begin{cases}
1&\qquad\text{if $P$ is true}\\
0&\qquad\text{if $P$ is false}
\end{cases}
\end{align*}
We can this way define
\begin{align*}
\color{blue}{\mathrm{Let}\ S:=[4>2]}
\end{align*}
which has the  advantage that since $S\in\{0,1\}$ it can be used in calculations.


text:
Q: How can you make a shape in html with css How can you make shapes using a single HTML element? Any CSS technique can be used as long as it's supported in at least one browser.
Examples of shapes would be a round shape, a triangle, six-angled and so on.

A: http://css3shapes.com/ has instructions on how to make a lot of shapes in CSS.
But seriously, there are better solutions to drawing shapes in the browser than using CSS.
Most of the shapes shown in the site above only work in modern browsers because they use CSS3 techniques that aren't available in browsers like IE8. (So if you want to do this in old versions of IE, the answer is forget about it).
But the same browsers that support those shapes also all support other technologies like SVG, which allow you to draw any shapes you like, without the restrictions of working around a box shape.
So the short answer is yes, it can be done, but SVG will give you much better results.

A: I have made this fiddle with some pure html/css shapes:
 - 2 triangles using a span border
 - a circle with the help of border-radius
Disclaimer: I was inspired from the old google application/menu bar.
Source:
html
An CSS triangle pointing down:

An CSS triangle pointing up:

Circle:

css
span.delta_down {
        border-color: #C0C0C0 transparent transparent;
        border-style: solid dashed dashed;
        border-width: 5px 5px 0;
        display: inline-block;
        font-size: 0;
        height: 0;
        line-height: 0;
        padding-top: 1px;
        position: relative;
        top: -1px;
        width: 0;
}

span.delta_up {
        border-color: transparent transparent #C0C0C0;
        border-style: dashed dashed solid;
        border-width: 0 5px 5px;
        display: inline-block;
        font-size: 0;
        height: 0;
        line-height: 0;
        padding-top: 1px;
        position: relative;
        top: -1px;
        width: 0;
}

span.circle {
        border-radius: 50%;
        width: 10px;
        height: 10px;
        display: inline-block;
        background-color: #C0C0C0;
}

A: This is not possible with pure HTML and CSS. But you can use a canvas element and draw all shapes with JavaScript.
This basic tutorial may help you.


text:
Q: Why does this JSON file get filled with 1747 times the last Hash data? I'm using the following code to generate a JSON file containing all category information for a particular website.
require 'mechanize'

@hashes = []

@categories_hash = {}
@categories_hash['category'] ||= {}
@categories_hash['category']['id'] ||= {}
@categories_hash['category']['name'] ||= {}
@categories_hash['category']['group'] ||= {}

# Initialize Mechanize object
a = Mechanize.new

# Begin scraping
a.get('http://www.marktplaats.nl/') do |page|
  groups = page.search('//*[(@id = "navigation-categories")]//a')

  groups.each_with_index do |group, index_1|
    a.get(group[:href]) do |page_2|
      categories = page_2.search('//*[(@id = "category-browser")]//a')

      categories.each_with_index do |category, index_2|
        @categories_hash['category']['id'] = "#{index_1}_#{index_2}"
        @categories_hash['category']['name'] = category.text
        @categories_hash['category']['group'] = group.text

        @hashes << @categories_hash['category']

        # Uncomment if you want to see what's being written
        puts @categories_hash['category'].to_json
      end
    end
  end
end

File.open("json/magic/#{Time.now.strftime '%Y%m%d%H%M%S'}_magic_categories.json", 'w') do |f|
  puts '# Writing category data to JSON file'
  f.write(@hashes.to_json)
  puts "|-----------> Done. #{@hashes.length} written."
end

puts '# Finished.'

But this code returns a JSON file filled with just the last category data. For the full JSON file take a look here. This is a sample:
[
   {
      "id":"36_17",
      "name":"Overige Diversen",
      "group":"Diversen"
   },
   {
      "id":"36_17",
      "name":"Overige Diversen",
      "group":"Diversen"
   },
   {
      "id":"36_17",
      "name":"Overige Diversen",
      "group":"Diversen"
   }, {...}
]

The question is, what's causing this and how can I solve it?

A: The same object, the result of @categories_hash['category'], is being updated each loop.
Thus the array is filled with the same object 1747 times, and the object reflects the mutations done on the last loop when it is viewed later.

While a fix might be to use @categories_hash[category_name] or similar (i.e. fetch/ensure a different object each loop), the following avoids the problem described and the unused/misused hash of 'category' keys.
categories.each_with_index do |category, index_2|
    # creates a new Hash object
    item = {
        id: "#{index_1}_#{index_2}",
        name: category.text,
        group: group.text
    }
    # adds the new (per yield) object
    @hashes << item
end

Alternatively, a more "functional" approach might be to use map, but it solves the problem in the same way - by creating new [Hash] objects. (This could be expanded to also include the outer loop, but it's just here for a taste.)
h = categories.each_with_index.map do |category, index_2|
    {
        id: "#{index_1}_#{index_2}",
        name: category.text,
        group: group.text
    }
end
@hashes.concat(h)


text:
Q: Load website in mobile app using web view import React, { Component } from 'react';
import { WebView } from 'react-native-webview';

class MyWeb extends Component {
render() {
return ( https://infinite.red' }} style={{ marginTop: 20 }} />
 );
} }

this is my code. I am trying to load a website using web view(react native) in mobile app.
Error: × Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of ExpoRootComponent

A: Try this
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';

// ...
class MyWebComponent extends Component {
  render() {
    return <WebView source={{ uri: 'https://infinite.red' }} style={{ marginTop: 20 }} />;
  }
}

You need to have a basic idea about the WebView package
API Documentation


text:
Q: Is it important to delete unused columns? My app includes two models that each have one column that the app is no longer using. I believe that I understand how to migrate them out of the database. And I don't think that it will take much work to migrate them out. But before I started working on that, I got curious. How much effect does each column have on the performance of the app? Are there other possible side-effects to leaving it there? I couldn't find these questions answered elsewhere.
Thanks for your thoughts,
Jeff

A: It does have effect:

*

*It takes db space

*Each time you're loading model, AR takes more resources to load all columns and create an object

*Most of read/write actions will take a tiny bit more time because of excessive column.

While this won't be palpable for a user, I would definitely go with removing the no longer used column.

A: You should remove it, the reason is

*

*This will take db space even its not required

*When some new guy will see and try to understand the usage of all column of this table, he might gets confused. So from readability and understanding point of view you should also remove the column. The column might also be part of triggers, stored procedures and indexes, so its important to clean up the unused column for a scalable product.

But remove it carefully, if it is being used in trigger, stored procedure and function then application might break.


text:
Q: Backend Testing response returning _body instead of body I am currently doing backend testing using Mocha Chai to test our mongoose backend. We have set up our tests using Gitlab Runner CI/CD and has suddenly started returning all commits as a failed test. We then try to retry old successful tests and still received failure upon retry. We also tried to run the test locally and it is returning as a successful test.
After further digging through the Gitlab Runner error log, we have found an assertion error caused by
 expect(testResult).to.include.keys("status", "body");

with the error code
 AssertionError: expected { Object (_events, _eventsCount, ...) } to contain keys 'status', and 'body'
  + expected - actual

   [
  -  "_body"
  -  "_events"
  -  "_eventsCount"
  -  "_maxListeners"
  -  "accepted"
  -  "badRequest"
  -  "buffered"
  -  "charset"
  -  "clientError"
  -  "created"
  -  "error"
  -  "files"
  -  "forbidden"
  -  "header"
  -  "headers"
  -  "info"
  -  "links"
  -  "noContent"
  -  "notAcceptable"
  -  "notFound"
  -  "ok"
  -  "pipe"
  -  "redirect"
  -  "redirects"
  -  "req"
  -  "request"
  -  "res"
  -  "serverError"
  -  "setEncoding"
  +  "body"
     "status"
  -  "statusCode"
  -  "statusType"
  -  "text"
  -  "type"
  -  "unauthorized"
  -  "unprocessableEntity"
  -  Symbol(kCapture)
   ]

I have tried changing our chai script to include.keys("status","_body") which solves the issue. However, it is unrealistic due to the amount of tests this sudden error is affecting. Furthermore, it would cause errors on our local testing. This issue started to appear on early January
Any suggestions on what might be causing the difference between response on Gitlab Runner and local testing?


text:
Q: Insert values to mysql Java It gives this error:

"java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0). "

This is the code:
public void insertData(int id,String name, String status, String age){

     String sql = "INSERT INTO student_table (id,name,satus,age) VALUES  (id,name,status,age)";

     try (Connection conn1 = this.connects();PreparedStatement Prepst= conn1.prepareStatement(sql)){

     Prepst.setInt(1, id);
     Prepst.setString(2, name);
     Prepst.setString(3, status);
     Prepst.setString(4, age);
     Prepst.executeUpdate();

     }catch(Exception e){
            System.err.println(e);

      }

If I   change  the parameter index to another value i.e.:
Prepst.setInt(0, id);

then it gives this error:

" java.sql.SQLException: Parameter index out of range (0 < 1 ). "

----UPDATE -----
I inserted this code:
String sql = "INSERT INTO student_table (id,name,satus,age) VALUES  (?,?,?,?)";

It produces the same:
RESULT
Table Structure:

A: Your SQL expression
INSERT INTO student_table (id,name,satus,age) VALUES  (id,name,status,age)

actually does not have any parameters. Try with:
INSERT INTO student_table (id,name,satus,age) VALUES  (?,?,?,?)

A: Try this...
public void insertData(int id,String name, String status, String age){

     String sql = "INSERT INTO student_table (id,name,satus,age) VALUES  (?,?,?,?)";

     try (Connection conn1 = this.connection;PreparedStatement Prepst= conn1.prepareStatement(sql)){

     Prepst.setInt(1, id);
     Prepst.setString(2, name);
     Prepst.setString(3, status);
     Prepst.setString(4, age);
     Prepst.executeUpdate();

     }catch(Exception e){
            System.err.println(e);

      }
}


text:
Q: Can we use spacy with MXnet Can we use spacy with MXnet to build a deep neural network(NLP)
We are building an application using mxnet. How to use spacy with Mxnet

A: Spacy and MXNet serialize their models differently so they are not directly compatible.
You can leverage the pre-trained models of Spacy as part of a preprocessing step for your text data though, and then feed into an MXNet model. Aim to get your text data into an NDArray format (using mx.nd.array).
Also take a look at MXNet's Model Zoo (https://mxnet.apache.org/model_zoo/index.html) which contains a number of models for NLP tasks; Word2Vec embedding being one example.


text:
Q: Fail on running Android Studio emulator with React Native on Windows instagramClone[instagram-clone]$ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 864 file(s) to forward-jetify. Using 4 workers...
info JS server already running.
/bin/sh: 1: /home/leyla/Android/Sdk/platform-tools/adb: not found
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of emulator -list-avds.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
FAILURE: Build failed with an exception.

*

*What went wrong:
A problem occurred configuring project ':app'.

The SDK directory '/mnt/c/Users/leylali/CodeFellows/401/react-native-learning/instagramClone/android/C:\Users\leylali\AppData\Local\Android\Sdk' does not exist.

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 6s
error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
FAILURE: Build failed with an exception.

*

*What went wrong:
A problem occurred configuring project ':app'.

The SDK directory '/mnt/c/Users/leylali/CodeFellows/401/react-native-learning/instagramClone/android/C:\Users\leylali\AppData\Local\Android\Sdk' does not exist.

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 6s
at checkExecSyncError (child_process.js:621:11)
at execFileSync (child_process.js:639:15)
at runOnAllDevices (/mnt/c/Users/leylali/CodeFellows/401/react-native-learning/instagramClone/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:39)
at processTicksAndRejections (internal/process/task_queues.js:85:5)


text:
Q: How can I update the data taken from the api using the updated context data? I have a simple online market; which get data from fake api. There is no "quantity" in this api, when I get the data I add the "quantity" to an array of objects that are passed out of the api and control the cart state based on the context.
Now I want to display the product quantity in the product list when the user clicks the "add to cart" button. But because the data on this page comes from api, I can't updat "quantity".
How can I display updated "quantity" on this page?!

const ProductSlider = () => {
const {cart} = useCart()
const [products, setProducts] = useState([])
useEffect(() => {
getProducts()
}, [])

const getProducts = async () => {
try {
  const {data} = await http.get("https://fakestoreapi.com/products")
  const newData = data.map((obj) => ({...obj, quantity: 0}))
  setProducts(newData.slice(0, 8))
} catch (error) {
  console.log(error)
}
}
return (

Latest Products

    <button>more</button>

  <Swiper
    freeMode={true}
    grabCursor={true}
    modules={[FreeMode]}
    className={styles.mySwiper}
    slidesPerView={4}
    spaceBetween={30}>
    {products.length ? (
      products.map((item) => (
        <SwiperSlide key={item.id}>
          <SingleProduct item={item} />
        </SwiperSlide>
      ))
     ) : (

Loading

    )}
   </Swiper>

   )
   }

there is no problem in cart page because data get from context.
const CartReducer = (state, action) => {
switch (action.type) {
case "ADD_TO_CART": {
  const updatedCart = [...state.cart]
  const itemIndex = updatedCart.findIndex(
    (item) => item.id === action.payload.id
  )
  if (itemIndex < 0) {
    const updatedItem = {...updatedCart[itemIndex]}
    updatedItem.quantity++
    updatedCart[itemIndex] = updatedItem
    updatedCart.push({...action.payload})
    // updatedCart.push({...action.payload, quantity: 1})
  } else {
    const updatedItem = {...updatedCart[itemIndex]}
    updatedItem.quantity++
    updatedCart[itemIndex] = updatedItem
  }
  return {...state, cart: updatedCart}
  }}

A: I solved this problem by passing "cart" to the CartControl component.
I found the clicked product in the cart and returned the quantity of this product.
const CartControl = ({add, remove, item, cart}) => {
const searchInCart = (cart, product) => {
const updatedProduct = cart.find((item) => item.id === product.id)
return updatedProduct.quantity
}
return (

  <button onClick={add}>+</button>
  {searchInCart(cart, item)}
  {searchInCart(cart, item) > 1 ? (
    <button className={styles.decQuantity} onClick={remove}>
      -
    </button>
   ) : (
    <button className={styles.red} onClick={remove}>
      <FaTrash />
    </button>
    )}

   )
   }

    export default CartControl


text:
Q: Qpid Proton CPP issue with exchanges I am having an issue with the most trivial step in Qpid Proton. Here's my setup
 qpid-config -a localhost:5672 add exchange test.announce
 qpid-config -a localhost:5672 add queue test.announce.q
 qpid-config -a localhost:5672 bind test.announce test.announce.q

(no routing key specified intentionally)
When I run the proton cpp server and client with the following
 ./server -a amqp://127.0.0.1:5672/test.announce
 ./client -a amqp://127.0.0.1:5672/test.announce.q

the client fails to communicate with the server. But using the standalone qpid tools
qpid-receive -a test.announce.q -b 127.0.0.1:5672  -t -f
echo "hello world!!!"|qpid-send -b 127.0.0.1:5672 -a test.announce -m 1 --content-stdin

this works as expected.
Running qpid-send against the Proton server also seems to work fine. I do not see anything in the Proton message API that I can update and not sure what I'm missing here. The server and client code are pretty much identical to what's in 0.12 snapshot. Any thoughts?

A: I realized my mistake. The concept of server and client in AMQP seem somewhat reversed. I changed the apps so that client "sent" on exchange while server listened on queue and everything worked.
 ./server -a amqp://127.0.0.1:5672/test.announce.q
 ./client -a amqp://127.0.0.1:5672/test.announce


text:
Q: Send next request when last one is done I have 100+ request.I need send a new request when the last one is done,so the server will not return error code - 429.
How to make this by afnetworking 3.0?

A: I'm not very familiar with the specific APIs of AFNetworking, but you could setup:

*

*A variable array containing all your pending requests,

*A method called (e.g.) sendNext() that removes the first entry of the array, performs the request asynchronously, and inside the completion block, calls itself.

Of course, you will need a terminating condition, and that is simply stop when the array becomes empty.

A: There are 2 approaches that can deal with your problem.
Firstly, create an operation queue and add all requests to the queue. After that, create an operation of your new request, then add the dependency to all requests in the queue. As a result, your new operation (will execute the new request) will be performed after the last request is done.
Secondly, you can use dispatch_barrier_async, which will create a synchronized point on your concurrent queue. That means you should create a concurrency queue to execute your 100+ request, and that dispatch_barrier_async blocks in your custom queue will execute the new request.

A: Thanks Sendoa for the link to the GitHub issue where Mattt explains why this functionality is not working anymore. There is a clear reason why this isn't possible with the new NSURLSession structure; Tasks just aren't operations, so the old way of using dependencies or batches of operations won't work.

I've created this solution using a dispatch_group that makes it possible to batch requests using NSURLSession, here is the (pseudo-)code:

// Create a dispatch group
dispatch_group_t group = dispatch_group_create();

for (int i = 0; i < 10; i++) {
    // Enter the group for each request we create
    dispatch_group_enter(group);

    // Fire the request
    [self GET:@"endpoint.json"
       parameters:nil
          success:^(NSURLSessionDataTask *task, id responseObject) {
                  // Leave the group as soon as the request succeeded
                  dispatch_group_leave(group);
          }
      failure:^(NSURLSessionDataTask *task, NSError *error) {
                  // Leave the group as soon as the request failed
                  dispatch_group_leave(group);
              }];
}

// Here we wait for all the requests to finish
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    // Do whatever you need to do when all requests are finished
});
I want to look write something that makes this easier to do and discuss with Matt if this is something (when implemented nicely) that could be merged into AFNetworking. In my opinion it would be great to do something like this with the library itself. But I have to check when I have some spare time for that.

A: This question possible duplicate of AFNetworking 3.0 AFHTTPSessionManager using NSOperation . You can follow @Darji comment for few call, For 100+ call add these utility classes https://github.com/robertmryan/AFHTTPSessionOperation/ .
It is very impractical approach to sent 100+ request operation concurrently. If possible try to reduce it.


text:
Q: tsc --build outputs same error multiple times I have the following project structure:
my-monorepo
├── tsconfig.json
└── packages
    ├── package-one
    │   └── index.ts: import packageThree from '@my-monorepo/package-three'
    ├── package-two
    │   └── index.ts: import packageThree from '@my-monorepo/package-three'
    └── package-three
        └── index.ts: // have some ts error

In that case tsb -b report error in pacakge-three pacakge x3 times.
The following settings do not help:
"skipLibCheck": true,
"exclude": ["node_modules"]

How do I get the typscript to scan only src files without delving into the dependencies?


text:
Q: C++ Comparing string to 0 using == operator? #include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int main()
{
  string A1;
  cin>>A1;
  if(A1==0)
   {
     cout<<"Success!";
   }
  else
   {
     cout<<"Failure!";
   }
system("PAUSE");
return 0;
}

Beginner in C++. I`m trying to compare the value of a string keyed in to 0 using the == operator. Above is my sample of code. How do I solve this problem in the simplest manner? Thank you.

A: Consider writing if(A1 == "0"). The C++ std::string class overloads the == operator to allow this.
To check if the string is empty, write if (A1.empty()) or if (!A1.size()).  I prefer the second formulation as it's consistent with other C++ standard library objects.
Personally I prefer to use the compare method on std::string instead. This makes your code more readable by other developers (e.g. Java developers would hate to see == in this context).

A: C++ is a strongly typed language. 0 by itself is a number. "0" is a string literal. There are functions which can do conversions, eg. std::stoi (String to Integer) and std::to_string (Lots of things to string), though.
So you have quite a few possible solutions here, to get the types equal. There's no real best solution for such a simplified case.


text:
Q: need to check oracle query executed from which machine I am developer and stated working in oracle database also now i have one query that is for development environment we are using common user named abc having same credentials so in a team of ten people we are using this same user to log in to oracle database  that is abc user
so please advise lets say if i want to track that which oracle query is fired by which machine that s i want to tack the machine name from which the oracle query is fired , then how can i track that.

A: create audit and look at audit trail, you may want to add a trigger to the AUD$ table to count logins, monitor for specific actions , or perform other security-related function
AUDIT_TRAIL = { none | os | db | db,extended | xml | xml,extended }


text:
Q: Android: Save the conversation during the call I want to ask whether it is possible in android to record an ongoing phone conversation. I was able to record what was being spoken in microphone, but not the audio coming from other end.
I tried it using MediaRecorder.AudioSource.VOICE_CALL value, but with no success.
Any help ????

A: There are many similar questions (Search for Android record call), but they all suggest that it's not possible with the current API without i.e. replacing the current phone application.


text:
Q: If $[G:H\cap K]= [G:H][G:K]$ then $G=HK$. Let $G$ a finite group and $H,K$ subgroups of $G$. Show that if $[G:H\cap K]= [G:H][G:K]$ then $G=HK$.
I proved that $G=HK$ implies $[G:H\cap K]= [G:H][G:K]$ but not the other direction.
Thanks for your help.

A: Hint: Use the fact that
$$|HK|=\frac{|H||K|}{|H\cap K|}.$$


text:
Q: Azure DevOps / Multiple projects I'm trying to get CICD ready using Azure DevOps. I have a big repo with 1 webapp, 2 azure functions and some others projects used as librairies. So I have 3 project to deploy, on different environnements.
I have only 1 .sln file, at the root of these projects.
I'm able to build all the projects, but I don't know how to get 1 particular built project (artifact ?) and deploy it.
- task: VSBuild@1
  inputs:
    solution: 'allproject.sln'
- task: PublishBuildArtifacts@1

I tried this, and I'm able to deploy the artifact on my release pipeline but when I have only one project built. Here I don't know how to procede.
Splitting my projects and create solution for each projects is a possibility, but if possible I would avoid this. Use MSBuild is possible too but I really want to avoid it because of the complexity (in the maintenance of the pipelines, we are a small team).

After GeralexGR awesome answer, I solved some of my problems but I cant solve the publication of the artifacts.
Here a screenshot of my problem
So I want to publish functionApp on the function app env, but I cant choose the artifact on the publication interface. Any idea ?

A: I have created a solution based on your description. In this setup I included a consoleApp and two functions apps inside the functions folder as shown below.

You can build your project as you could do on visual studio and each project will contain the output bin and obj folders with the artifact.

You should then decide your strategy regarding how you should proceed. For example you could upload all ArtifactsStagingDirectory or each folder separate.
YAML pipeline:
trigger:
- none

pr: none

pool:
  vmImage: ubuntu-latest

steps:

- task: UseDotNet@2
  inputs:
    packageType: sdk
    version: '6.0.x'
    includePreviewVersions: true

- task: DotNetCoreCLI@2
  displayName: Building .NET project
  inputs:
    command: 'build'
    projects: '**/*.csproj'
    arguments: '--configuration debug'

Test step to locate the structure:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      # Write your PowerShell commands here.

      cd "$(Pipeline.Workspace)/s"
      ls

Inside functions and consoleapp projects you can locate the build artifacts.


text:
Q: CloudFormation syntax for ParameterOverrides I'm getting stuck on overriding multiple parameters within a CloudFormation that is passing them to CodePipeline.
I can successful override a single parameter like this:
ParameterOverrides: "{ \"StageName\": \"stage\" }"

But when I try this:
ParameterOverrides: '{ "StageName": "prod", "EnvValue", "prod" }'

I have also tried these combinations:
ParameterOverrides: "{\"StageName\": \"prod\", \"EnvValue\", \"prod\"}"

Codepipeline throws an error of: ParameterOverrides property is not valid
I have looked at this help article a half a dozen times and it seems I'm following the format to the T.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/continuous-delivery-codepipeline-parameter-override-functions.html
What am I missing? Does anyone have this working in a CloudFormation template?

A: When dealing with embedded JSON in your YAML, the folded (>) or literal (|) block style, rather than a quoted string, will increase clarity. So something like:
ParameterOverrides: >
  {
    "StageName": "prod",
    "EnvValue": "prod"
  }

This will let you see the actual JSON without quite as much noise from the backslash escapes in the way. This can be seen in the "Example Create Stack B Stage" section of the page you linked to (it uses the literal block style with |). The difference between | and > can be seen on the YAML Multiline site.

A: I found out what the problem was, fat fingered.
I put this:
ParameterOverrides: "{\"StageName\": \"prod\", \"EnvValue\", \"prod\"}"

and it should have been this:
ParameterOverrides: "{\"StageName\": \"prod\", \"EnvValue\": \"prod\"}"

NOTICE: the missing colon on after the second key.


text:
Q: Older AppleTV 4K started having decoding artifacts a few months back. Factory reset didn't help. Is it just my device? I have an A1842 AppleTV 4K (one of the first versions) that I have been very satisfied with and which functions as expected.   A few months back I started noticing that the edges around persons in movies were ... strangely fuzzy when moving, but was unable to identify it closer.   Resetting the device back then didn't change anything, nor resolution change, display update speed or anything else.
Now I found that the Disney movie "The Three Musketeers" that I bought from iTunes store showed this very clearly (on this device, all my other Apple devices are fine) and made a clip out of it.  This screenshot shows an artifact in front of Goofys face.

The whole clip is at whole clip (I do not know how to add video to questions, please edit it in if you do).
Has anyone else seen this?  If yes, is it a known problem, which can be fixed?
Note: the appletv is connected directly to a 4K tv with a modern cable.
2022-07-21: Now a bit later I've even seen artifacts in subtitles (which are put "on top" of the decoded movie stream in the AppleTV itself) which only makes sense to me if either Dolby Vision has a compression scheme that somehow breaks or the AppleTV GPU driver has a bug.

A: It appears that Dolby Vision was the culprit.  Turning that off on the Apple TV and going back to HDR removed the artifacts.
After having power cut to both TV and AppleTV the problem returned.  Changing resolution etc didn't work, but resetting video settings did.  This is highly unsatisfactory, and my answer is therefore not a real answer yet.
My TV is a very cheap Philips som this problem might be something not present on more expensive devices.


text:
Q: Password isn't getting hashed by brcypt module I am hashing password using nodejs "bcrypt" module. this is my hashing function...

 and here i am calling my function

But in databases password is not saving. In databases field is empty every time when i register. How can i fix it?
Here is database entry record

A: You have nothing saved inside your database because you choose to use the asynchronous bcrypt hash function.
It should work if you use the synchronous one. ( replace your bcrypt hash by this one)
let hash = bcrypt.hashSync('password', 10);
return hash;


text:
Q: how can i use django filter with multiple value select I want to filter my data based on city , how can i filter my data if the user choose more than one city using django filter
class games(generics.ListAPIView):
queryset = Game.objects.filter(start_date__gte=datetime.today())
serializer_class=GameSerializers
filter_backends = [DjangoFilterBackend,filters.OrderingFilter]
filterset_fields = ['id','city','level']

game model
class Game(models.Model):
city = models.CharField(max_length=255)
gender = models.ForeignKey(Gender,on_delete=models.CASCADE)
level = models.ForeignKey(Level,on_delete=models.CASCADE)
host = models.ForeignKey(Host,on_delete=models.CASCADE)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
fees = models.IntegerField()
indoor = models.BooleanField()
capacity = models.IntegerField()
age_from = models.IntegerField()
age_to = models.IntegerField()
description =  models.CharField(max_length=255)
earned_points = models.IntegerField()
created_at = models.DateTimeField(default=django.utils.timezone.now)
image = models.ImageField(upload_to="GameImage",null=True)
history = HistoricalRecords()

A: Game.objects.filter(city__in=['Paris', 'London'])

Something like that ?

A: I'm not sure if this gonna work but try this:
filterset_fields = ['id','city__in','level']


text: Q: Changing line properties in visio I want to change the connector style from solid line to dashed line in visio 2013. Even if I change from line properties, the change is not happening. How do I do that?


text:
Q: Microsoft Teams overwritten hotkeys I have installed Microsoft Teams application and it has overwritten hotkeys like Alt+a, Alt+c and doesn't allow me to change them in application settings.
The problem is that these hotkeys are reserved in Polish language for diactrical characters so if I have opened Teams application I can't use these characters.
Do you know any solution to not allow application to overwrite default hotkeys?

A: This problem has been reported to Microsoft and they say they are working on it.
You can follow progress at https://microsoftteams.uservoice.com/forums/555103-public/suggestions/32520820-teams-has-hijacked-several-keyboard-shortcuts


text:
Q: importing value to another class     btnRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                registerUser(name, email, password);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
            return name;              //<-here is the error
        }

i want to import "name" to another class.. How Can i do this?

A: I guess you want to send the value to another activity, right? Then you should use intents.
In your activity:
Intent intent = new Intent();
intent.putExtra("name", name);
startActivity(intent);

In the activity where you want to get the value:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String data = extras.getString("name");

A: Easiest way to do it is via intents.
You can set up an intent for the class you want to launch. Then you can put the name as extra and start the activity class.
Intent intent = new Intent(this,YourActivityClass.class);
intent.putExtra("Name","value");
startActivity(intent);

A: You can also use preference to store and retrieve datas wherever you need.
For eg: this is in Utils class.
 private Editor mEditor;
  private SharedPreferences mPreferences;
     private static final String PREFERENCE_NAME = "pref";
  public Utils(Context context) {
    mPreferences = context.getSharedPreferences(PREFERENCE_NAME,
            Context.MODE_PRIVATE);
    mEditor = mPreferences.edit();
}

    /**
 * Store string in preference.
 *
 * @param key
 *            the key
 * @param value
 *            the value
 */
public static void storeStringInPreference(String key, String value) {
    mEditor.putString(key, value);
    mEditor.commit();
}

/**
 * Gets the string from preference.
 *
 * @param key
 *            the key
 * @return the string from preference
 */
public static String getStringFromPreference(String key) {
    return mPreferences.getString(key, null);
}

In Activity A:
String password = inputPassword.getText().toString();
Utils.storeInPreference("password",password); //key,value

 In Activity B:

String password = Utils.getStringFromPreference("password"); //key


text:
Q: Kubernetes source docker files Trying to understand how a cluster is being setup and how different components of the cluster work together, I am looking into different Kubernetes yaml files in particular the kubeapi-server. There I can see that the image is coming from:
kube-apiserver:
    Container ID:  docker://fac3b6468d5d60c0a5154ac1659d447255467d951522ce6d82c6b9438a6e5c89
    Image:         k8s.gcr.io/kube-apiserver:v1.21.2
    Image ID:      docker-pullable://k8s.gcr.io/kube-apiserver@sha256:c86c3855e360b1483008c30c8deaed2b1a92f63eaacec819a90a0ffe04df152b

So, I know the image itself is stored on k8s.gcr.io and I can reach that but I cannot see the source code for the actual Dockerfile while I assume it should be open source and available in some repo, like for example nginx and alpine where the link to their github is mentioned on the docker hub:

*

*https://hub.docker.com/_/nginx?tab=description

*https://hub.docker.com/_/alpine
I hope someone knows where to find the Kubeapi-server and other kube* docker image source files.
Update 1:
I did some more investigation on the locally stored docker image on my machine to check the base image etc like below:
docker image ls | grep apiserver
k8s.gcr.io/kube-apiserver                                                                        v1.21.2      106ff58d4308   6 months ago    126MB

docker image history 106ff58d4308

.... (big output but shows the some info about layers and ENTRYPOINT which points to a base image name)

But what I want is still the Dockerfile source code.


text:
Q: Google Glass GDK: How to communicate with an iOS device? Right now it appears there is no Bluetooth LE support in the GDK.
We are looking to transmit realtime athletic performance data from an iOS device to Glass.
StackOverflow refers to a Github library for Android to Glass connections using Bluetooth.
Theoretically could this be modified to work on iOS? Or is there any other protocol or approach in the GDK that would support sending data streams to Glass from iOS devices that have no Internet connection?  (i.e. such as an iPad on a golf course, soccer field etc.)

A: It appears that this is possible based on the documentation found here:
https://support.google.com/glass/answer/3064189

From an iPhone:

To turn on Bluetooth on your iOS device and pair your Glass, follow
  the steps in Apple Support. All of the functionality of Glass is
  available via your iPhone's Bluetooth connection, with the exception
  of SMS and turn-by-turn directions. These features require the MyGlass
  app, which is only available for Android.

Since the pairing there would have to be done via normal Bluetooth paring mechanisms, it stands to reason that you ought to be able to utilize the normal blue tooth protocols to implement cross platform communication.
I can't swear to this as I'm not an IOS dev, but if you're able to pair, then you're through the normal Android-IOS bluetooth profile issues which limit this kind of data transfer normally.  You would obviously have to write host code on the Phone and such


text:
Q: How can I automate my usage of three VM machines with the same alias? How do I automate my usage of three VM machines which require me to add a IP aliased to a name in my HOSTS file. I upload code to the server of choice and then I go to the address http:/ / serverVM/blah and view the program. The basic idea is that I want to be able to add multiple IP addresses in my HOSTS file all with the same alias "serverVM", so that no matter which server I use, I don't have to modify my HOSTS and reboot.
So example:

192.168.1.1 serverVM
  192.168.1.2 serverVM
  192.168.1.3 serverVM

You might ask why I don't just do: http:/ / 192.168.1.2/blah? Well it's because the application I use requires the alias "serverVM" because of a cookie and the application won't work correcly otherwise.
The problem is I don't think this is possible with the HOSTS file. Each server is different and I want to chose which one to use at any given time, I can't just use any of them.
Is there a way to solve my dilemma?

A: Download Fiddler and the Syntax-Highlighting Addon. Open the program once thet have been installed.  Fiddler is an HTTP proxy which allows you to modify HTTP requests before they are sent to the server.
In Fiddler select the "Fiddler Script" tab.  Find the OnBeforeRequest function and add the following code inside that method:
if(oSession.hostname.Contains("serverVM"))
{
    var prev = oSession.hostname,
        newIp = prev;

    oSession.hostname = "serverVM";

    if(prev == "serverVM1") {
        newIp = "192.168.1.1";
    } else if(prev == "serverVM2") {
        newIp = "192.168.1.2";
    } else if(prev == "serverVM3") {
        newIp = "192.168.1.3";
    }

    oSession["x-overrideHost"] = newIp;
}

Now you should be able to access your three differnt servers using http://serverVM1, http://serverVM2 and http://serverVM3.

A: I gave up on this mostly, as I don't need to access so many machines after all and I found out I can simply close my browser and reopen it when I modify my hosts file.


text:
Q: table not updating even the property is deleted I have EF in my project. I was trying to add FK (ServiceID) in the model and it was added but now im trying to remove it it doesn't change anything. I tried adding new property(TestProp) and then remove it and it works fine unlike the ServiceID. Why?
What I have done is:

*

*Remove the property

*Add-Migration mymigration

*update-database


text:
Q: Finding surface normal for 3D region at a specific point I would like to find the surface normal for a point on a 3D filled shape in Mathematica.
I know how to calculate the normal of a parametric surface using the cross product but this method will not work for a shape like Cone[] or Ball[].

*

*Is there some sort of RegionNormal option? There is an option to
find VertexNormals here, but this is something to with
shading and seems unhelpful.

*Is there a method I can use to convert the region into a parametric expression and use the normal cross product method?

The plan is to take an arbitrary line and find the angle of intersection between the line and the surface of the shape.

A: (* put inequality into u ≤ 0 form, return just u *)

standardize[a_ <= b_] := a - b;
standardize[a_ >= b_] := b - a;
regnormal[reg_, {x_, y_, z_}] := Module[{impl},
   impl = LogicalExpand@ Simplify[RegionMember[reg, {x, y, z}], {x, y, z} ∈ Reals];
   If[Head@impl === Or,
    impl = List @@ impl,
    impl = List@impl];
   impl = Replace[impl, {Verbatim[And][a___] :> {a}, e_ :> {e}}, 1];
   Piecewise[
    Flatten[
     Function[{component},
       Table[{
         D[standardize[component[[i]]], {{x, y, z}}],
         Simplify[
          (And @@ Drop[component, {i}] /. {LessEqual -> Less, GreaterEqual -> Greater}) &&
           (component[[i]] /. {LessEqual -> Equal, GreaterEqual -> Equal}),
          TransformationFunctions -> {Automatic,
            Reduce[#, {}, Reals] &}]
         }, {i, Length@component}]
       ] /@ impl,
     1],
    Indeterminate]
   ];

Examples:
regnormal[Cone[{{0, 0, 0}, {1, 1, 1}}, 1/2], {x, y, z}]

regnormal[Ball[{1, 2, 3}, 4], {x, y, z}]

regnormal[RegionUnion[Ball[], Cone[{{0, 0, 0}, {1, 1, 1}}, 1/2]], {x, y, z}]

regnormal[Cylinder[{{1, 1, 1}, {2, 3, 1}}], {x, y, z}]

It assumes that the RegionMember expression can be computed (which is not always the case) and that it will be a union (via Or) of intersections (via And).  It also assumes that the RegionMember expression includes the boundary.  Thus, it is probably not very robust, but it handles the OP's examples.
Also, if this is used in numerical applications, which seems to be the case for the OP, one should worry about the exact conditions in the Piecewise expressions returned.  It's unlikely the numerical calculations will be accurate enough to satisfy Equal.  So either change the conditions or possible change Internal`$EqualTolerance:
Block[{Internal`$EqualTolerance = Log10[2.^28]}, (* ~single-precision FP equality *)
 <evaluate regnormal[...] expression>
 ]

A: Wether this is enough to warrant an "answer" is debatable and it relies on MichaelE2's work, but I felt it was helpful to share.
Using Michael E2's solution, we can plot and clearly see the normals for 3D shapes.
numberofpoints = 50;
pts = RandomPoint[RegionBoundary[shape], numberofpoints];
normals = regnormal[shape, {x, y, z}]
surfaces = Length[normals[[1]]];
magnitude = 0.1;

pointonsurface = ConstantArray[0, surfaces];

lines[{a_, b_}] :=  {magnitude*normals[[1, a, 1]] + b,
    b} /. {x -> b[[1]], y ->  b[[2]], z -> b[[3]]};

For[i = 1, i <= surfaces, i++,

 pointonsurface[[i]] =
  Table[ {If[
     Evaluate[
       normals[[1, i, 2]] /. {x -> pts[[j, 1]], y ->  pts[[j, 2]],
         z -> pts[[j, 3]]}] == True, i], pts[[j]]}, {j, 1,
    numberofpoints, 1}];

 pointonsurface[[i]]  =
  DeleteCases[pointonsurface[[i]], {a_, b_} /; a == Null];
 pointonsurface[[i]] = lines /@ pointonsurface[[i]];

 ]

normallines = Flatten[pointonsurface, 1];

Graphics3D[{shape, {Red, Point[pts]}, Line[normallines] },
 Boxed -> False, Axes -> True, PlotRange -> All]

So, for Cone[]

And for Cuboid[]

And for Sphere[]

A: If you know the equation of your surface, you can do this.  For instance a circle at the origin of radius 5.
f[x_,y_,z_]=x^2+y^2+z^2-5^2;

grad[x_,y_,z_]=Grad[f[x,y,z],{x,y,z}]

The unit normal vector on that surface is
normal[x_,y_,z_]=Simplify[grad[x,y,z]/Sqrt[grad[x,y,z].grad[x,y,z]]]

Simple case
normal[0,0,5]
(*{0,0,1}*)

normal[2,3,2 Sqrt[3]]
(*{2/5,3/5,(2 Sqrt[3])/5}*)

The hard part is getting the surface into the equation.

A: I just came across the UnitNormal[] function that might be applicable:
https://resources.wolframcloud.com/FunctionRepository/resources/UnitNormal
Also, SurfaceData[surface,"NormalVector"] might work:
https://reference.wolfram.com/language/ref/SurfaceData.html


text:
Q: Is Ext.ComponentQuery.query a time consuming process to access component Currently i am using Ext.ComponentQuery.query method to access components using id.So just wanted to know if it is safe (proper) way to access components.

A: When using Id the Ext.getCmp is probably better\faster option then component query.
As stated on other places,

be wary of using id's, since they need to be globally unique

Using them in your code makes your components really hard to reuse (you cant create two instances of component on the same page for example). For reasonable complex ExtJS app I strongly suggest to use MVC app architecture. Although MVC model in ExtJS 4.x is far from perfect and i personally use DeftJS which offers not just improved MVC model but also IoC and Promises and community support is awesome!


text:
Q: Inheriting an interface so add a setter to an existing property I was hoping to use inheritance to add a setter to an existing property. I want to do something like this:
public class MyObjectRepository<T> : IObjectRepository<T> where T : IRepositoryEntity
{
    private readonly List<T> _data = new List<T>();
    // ...
    public void Add(T model)
    {
        _data.Add(model);

        var managedModel = (IManagedRepositoryEntity)model;
        if (managedModel != null)
            managedModel.SetId(_data.LastIndexOf(model));
    }
    // ...
}

public interface IRepositoryEntity
{
    object Id { get; }
}

public interface IManagedRepositoryEntity : IRepositoryEntity
{
    void SetId(object id);
}

That works I guess, but I don't like that SetId business. I would like to do something like this instead, but alas, C# won't let me:
public interface IRepositoryEntity
{
    virtual object Id { get; }
}

public interface IManagedRepositoryEntity : IRepositoryEntity
{
    override object Id { get; set; }
}

A: virtual and override are not valid in interface definitions, you need
public interface IRepositoryEntity
{
   object Id { get; }
}

public interface IManagedRepositoryEntity : IRepositoryEntity
{
    new object Id { get; set; }
}


text:
Q: How to detect one 3D mesh part contained within the other 3D mesh part I need to detect if one part contains another part.
Imagine a shape such as closed Mail Box with some small holes in it. This Mail Box shape contains a Tea Pot inside. What would be an approach to detect that Tea Pot 3D mesh object is contained within closed Mail Box 3D mesh object. I cannot remove Tea Pot from closed Mail Box with only small holes in it. This is opposite to Open Mail Box. I can easily remove Tea Pot from open Mail Box object.

A: Depending on what you're trying to achieve you might want to start more coarsely. For example, you should be able to determine if the bounding box of the teapot is within the bounding box of the mailbox. If you need more fine-grained tests for other objects, you can then go to the convex hulls of the 2 objects and test whether one is within the other.


text:
Q: Tkinter: changes made to global variable don't stay Whenever I press on one of the buttons created, the procedure that's run does initially change the values of the global variables, but once the procedures finish execution they for some reason revert back. Here's the code:
from tkinter import *

transformEnabled,selectionEnabled,paintEnabled = False,False,False

root = Tk()

def hide(tool,toolkit):
    for i in toolkit:
        i.grid_forget()
    tool=False
def toolkitFunctions(tool1,tool2,tool3,toolkit1,toolkit2,toolkit3):
    print(tool1)
    if tool1 == False:
        print("Before other tools set to false: ",str(tool1))
        if tool2:
            hide(tool2,toolkit2)
        if tool3:
            hide(tool3,toolkit3)
        for i in range(0,len(toolkit1)):
            toolkit1[i].grid(row=i+4,column=0)
        tool1=True
        print("After other tools set: ",str(tool1))
    else:
        print("If tool1 already true: ",str(tool1))
        hide(tool1,toolkit1)

#Transform Buttons
transformNames = ["Scale Image","Rotate Image","Move Image","Flip Image","Sharpen/Soften Image","Brightness/Constrast"]
transformButtons = [Button(root,text=transformNames[i],width=20) for i in range(0,len(transformNames))]
#SelectionButtons
selectionNames = ["Regular Shape Selection","Free hand Tool","Colour Picker"]
selectionButtons = [Button(root,text=selectionNames[i],width=20) for i in range(0,len(selectionNames))]
#Paint Buttons
paintNames = ["Paintbrush","Airbrush","Pencil","Eraser","Fill","Smudge","Dodge and Burn"]
paintButtons = [Button(root,text=paintNames[i],width=20) for i in range(0,len(paintNames))]

def transformFunctions():
    toolkitFunctions(transformEnabled,selectionEnabled,paintEnabled,transformButtons,selectionButtons,paintButtons)
def selectionFunctions():
    toolkitFunctions(selectionEnabled,transformEnabled,paintEnabled,selectionButtons,transformButtons,paintButtons)
def paintFunctions():
    toolkitFunctions(paintEnabled,transformEnabled,selectionEnabled,paintButtons,transformButtons,selectionButtons)

transform = Button(root,text="Transform Tools",width=20,command=transformFunctions).grid(row=3,column=0)
selection = Button(root,text="Selection Tools",width=20,command=selectionFunctions).grid(row=2,column=0)
paint = Button(root,text="Paint tools",width=20,command=paintFunctions).grid(row=1,column=0)

root.mainloop()

Is there anything that can be done to rectify this?

A: You send value from global variable transformEnabled to function but for string/int/float/boolean Python doesn't keep reference to original variable but it copies values to new variable.
You could use global transformEnabled in function and change directly transformEnabled = True to assign value to global variable. But your complex is too code for this simple method.
In your code it is better to keep values in global dictionary and send strings "transform", "selection", "paint" and use them to access data in this global dictionary.
It is big change in code but you need it. Eventually you could try to use classes to create widget which keep buttons and values for one type of functions. You could also use Frame to group buttons and show/hide this frame.

I changed other things in code - based on PEP 8 -- Style Guide for Python Code
import tkinter as tk

# --- functions --- (lower_case_names)

def hide(toolkit):
    for item in toolkit:
        item.grid_forget()

def show(toolkit):
    for i, item in enumerate(toolkit):
        item.grid(row=i+4, column=0) # maybe len(settings) instead of `4` so it will be works when you add more data in dictionary.

def on_click(name):

    print('--- before ---')
    for key, value in settings.items():
        print('{} enabled: {}'.format(key, value['enabled']))

    print('--- changes ---')
    if not settings[name]['enabled']:
        # hide other buttons
        for key, value in settings.items():
            print("Check:", key, key != name, value['enabled'])
            if key != name and value['enabled']:
                hide(value['buttons'])
                value['enabled'] = False

        # show buttons for `name`
        print("Show:", name)
        show(settings[name]['buttons'])
        settings[name]['enabled'] = True
    else:
        # hide buttons for `name`
        print("Hide:", name)
        hide(settings[name]['buttons'])
        settings[name]['enabled'] = False

# --- main --- (lower_case_names)

settings = {
    'transform': {
        'enabled': False,
        'names': ["Scale Image", "Rotate Image", "Move Image", "Flip Image", "Sharpen/Soften Image", "Brightness/Constrast"],
        'buttons': [],
    },
    'selection': {
        'enabled': False,
        'names': ["Regular Shape Selection", "Free hand Tool", "Colour Picker"],
        'buttons': [],
    },
    'paint': {
        'enabled': False,
        'names': ["Paintbrush", "Airbrush", "Pencil", "Eraser", "Fill", "Smudge", "Dodge and Burn"],
        'buttons': [],
    },
}

root = tk.Tk()

settings['transform']['buttons'] = [tk.Button(root, text=item, width=20) for item in settings['transform']['names']]

# Selection Buttons
settings['selection']['buttons'] = [tk.Button(root, text=item, width=20) for item in settings['selection']['names']]

# Paint Buttons
settings['paint']['buttons'] = [tk.Button(root, text=item, width=20) for item in settings['paint']['names']]

transform = tk.Button(root, text="Transform Tools", width=20, command=lambda:on_click('transform'))
transform.grid(row=3, column=0)

selection = tk.Button(root, text="Selection Tools", width=20, command=lambda:on_click('selection'))
selection.grid(row=2, column=0)

paint = tk.Button(root, text="Paint Tools", width=20, command=lambda:on_click('paint'))
paint.grid(row=1, column=0)

root.mainloop()

EDIT: The same code but buttons are create with loop. And I use len(settings) instead 4 to remove buttons - this way I could add Help menu to dictionary without changing other code.
import tkinter as tk

# --- functions --- (lower_case_names)

def hide(toolkit):
    for item in toolkit:
        item.grid_forget()

def show(toolkit):
    for i, item in enumerate(toolkit):
        item.grid(row=i+len(settings), column=0)

def on_click(name):

    print('--- before ---')
    for key, value in settings.items():
        print('{} enabled: {}'.format(key, value['enabled']))

    print('--- changes ---')
    if not settings[name]['enabled']:
        # hide other buttons
        for key, value in settings.items():
            print("Check:", key, key != name, value['enabled'])
            if key != name and value['enabled']:
                hide(value['buttons'])
                value['enabled'] = False

        # show buttons for `name`
        print("Show:", name)
        show(settings[name]['buttons'])
        settings[name]['enabled'] = True
    else:
        # hide buttons for `name`
        print("Hide:", name)
        hide(settings[name]['buttons'])
        settings[name]['enabled'] = False

# --- main --- (lower_case_names)

settings = {
    'transform': {
        'title': "Transform Tools",
        'enabled': False,
        'names': ["Scale Image", "Rotate Image", "Move Image", "Flip Image", "Sharpen/Soften Image", "Brightness/Constrast"],
        'buttons': [],
    },
    'selection': {
        'title': "Selection Tools",
        'enabled': False,
        'names': ["Regular Shape Selection", "Free hand Tool", "Colour Picker"],
        'buttons': [],
    },
    'paint': {
        'title': "Paint Tools",
        'enabled': False,
        'names': ["Paintbrush", "Airbrush", "Pencil", "Eraser", "Fill", "Smudge", "Dodge and Burn"],
        'buttons': [],
    },
    'help': {
        'title': "Help",
        'enabled': False,
        'names': ["Help ...", "Home Page", "About"],
        'buttons': [],
    },
}

root = tk.Tk()

for i, name in enumerate(['paint', 'selection', 'transform', 'help']): # it could be `enumerate(settings.keys())` but sometimes it may not keep order.
    settings[name]['buttons'] = [tk.Button(root, text=item, width=20) for item in settings[name]['names']]
    button = tk.Button(root, text=settings[name]['title'], width=20, command=lambda arg=name:on_click(arg))
    button.grid(row=i, column=0)

root.mainloop()


text:
Q: A request by user by browser and why more requests made when i open a site and submit a form, the browser show the response content.
but after i sniff by fiddler, i found more get/post requests sent by browser or js and they are not sent by ajax because no XMLHttpRequest in header. the response content-type are text/html.
so browser should show the new response content,right? but NOT. it still show the first.
1, how browser send more request? i guess they are made by javascript.
2, why browser did not show new content?

A: *

*Yes it does sound like a client-side scripting language, most likely JavaScript;

*It can be an AJAX load. AJAX does not have to be XMLHttpRequest, although most ajax implementations use XMLHttpRequest.


text:
Q: Why can't I open Visual Studio Code on Linux? I have worked on it for a whole week, but I can't still solve the problem.
Each time I install Visual Studio by yum install code-**x86_64.rpm.
After that, I write the command code on my terminal, but nothing happens!
I have remade CentOS7 five times and reinstalled Visual Studio Code more than 10 times.

A: Try this command sudo yum install code.
For more details, you can visit Visual Studio Code docs for Linux
And if you want to open the project you can use code . command in terminal, but make sure your terminal should be in project directory.


text:
Q: jQuery JSONP - error with a callback outside done() I'm on jQuery 1.8.2 and I'm doing a JSONP call like this:
    function foo(data) {
      console.log(data)
    }

    $.ajax({
      type: 'GET',
      url: http://xxx.cloudfront.net/posts.json?category=News&callback=foo,
      dataType: 'jsonp',
      cache: true,
      jsonp: false
    }).done(function (data) {

    }).fail(function (XHR, status, error) {
      console.log(error);
    });

When I run this the proper data response gets returned to the foo callback. But the error also fires, and the console logs the error as Error {}. From reading elsewhere on Stackoverflow  it appears this is because the response is wrapped in the callback and jQuery's expecting plain JSON. Should I just ignore this error?

A: You should not have a global function foo that is the callback, but let jQuery create that global function automatically and pass the result to the done callbacks. It does expect that its own function gets called, otherwise it triggers the error.
$.ajax({
  type: 'GET',
  url: "http://xxx.cloudfront.net/posts.json?category=News&callback=?",
  dataType: 'jsonp',
  jsonpCallback: 'foo', // for caching
  cache: true
}).done(function (data) {
  console.log(data);
}).fail(function (XHR, status, error) {
  console.log(error);
});

A: You've specifically removed the JSONP callback from your AJAX call, try omitting jsonp : false from the options object you pass into $.ajax and then removing the callback function you've created (foo) and let jQuery do the work for you.
Documentation is found here: http://api.jquery.com/jquery.ajax/


text:
Q: Unable to install dependencies with composer inside Docker image I was trying to install attendize by using docker.
when I put this command :
$ docker run --rm -v $(pwd):/app composer/composer install

then I got this error messages.
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - symfony/class-loader v3.4.8 requires php ^5.5.9|>=7.0.8 -> your PHP version (7.0.7) does not satisfy that requirement.
    - symfony/class-loader v3.4.8 requires php ^5.5.9|>=7.0.8 -> your PHP version (7.0.7) does not satisfy that requirement.
    - Installation request for symfony/class-loader v3.4.8 -> satisfiable by symfony/class-loader[v3.4.8].

This is my composer.json:
{
    "name":"attendize/attendize",
    "description":"A free and open-source event management and ticket selling application.",
    "keywords":[
        "event management",
        "ticket selling",
        "tickets",
        "events"
    ],
    "license":"Attribution Assurance License",
    "type":"project",
    "homepage":"https://www.attendize.com",
    "require":{
        "laravel/framework":"5.2.*",
        "laravelcollective/html":"~5.0",
        "milon/barcode":"dev-master",
        "iron-io/iron_mq":"2.*",
        "intervention/image":"dev-master",
        "nitmedia/wkhtml2pdf":"dev-master",
        "maatwebsite/excel":"~2.0.0",
        "dompdf/dompdf":"dev-master",
        "laravel/socialite":"~2.0",
        "filp/whoops":"~1.0",
        "vinelab/http":"dev-master",
        "mews/purifier":"~2.0",
        "league/flysystem-aws-s3-v3":"~1.0",
        "maxhoffmann/parsedown-laravel":"dev-master",
        "omnipay/common":"~2.3",
        "omnipay/stripe":"*",
        "omnipay/paypal":"*",
        "omnipay/bitpay":"dev-master",
        "omnipay/coinbase":"dev-master",
        "laracasts/utilities":"^2.1",
        "predis/predis":"~1.0",
        "guzzlehttp/guzzle":"^6.2",
        "omnipay/migs":"^2.1",
        "mcamara/laravel-localization":"^1.2",
        "potsky/laravel-localization-helpers":"2.3.*"
    },
    "require-dev":{
        "phpunit/phpunit":"~4.0",
        "phpspec/phpspec":"~2.1",
        "fzaninotto/faker":"^1.5",
        "symfony/dom-crawler":"~3.0",
        "symfony/css-selector":"~3.0",
        "doctrine/dbal":"~2.3",
        "barryvdh/laravel-ide-helper":"^2.1"
    },
    "autoload":{
        "classmap":[
            "database",
            "app/Http/Controllers",
            "app/Models",
            "app/Attendize"
        ],
        "psr-4":{
            "App\\":"app/",
            "Attendize\\":"app/Models"
        }
    },
    "autoload-dev":{
        "classmap":[
            "tests/TestCase.php"
        ]
    },
    "scripts":{
        "post-install-cmd":[
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd":[
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd":[
            "php -r \"copy('.env.example', '.env');\"",
            "php artisan key:generate"
        ]
    },
    "config":{
        "preferred-install":"dist"
    },
    "extra":{
        "laravel":{
            "dont-discover":[
                "potsky/laravel-localization-helpers"
            ]
        }
    }
}

I have no idea what is the problem because I am totally new.
please help me
thank you.
#docker-composer.yml

version: '2'

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile-nginx
    ports:
    - "8080:80"
    networks:
      - attendizenet
    volumes:
      - .:/usr/share/nginx/html/attendize
    depends_on:
      - php
  php:
    build:
      context: .
      dockerfile: Dockerfile-php
    depends_on:
      - db
      - maildev
      - redis
    volumes:
      - .:/usr/share/nginx/html/attendize
    networks:
      - attendizenet
  php-worker:
    build:
      context: .
      dockerfile: Dockerfile-php
    depends_on:
      - db
      - maildev
      - redis
    volumes:
      - .:/usr/share/nginx/html/attendize
    command: php artisan queue:work --daemon
    networks:
      - attendizenet
  db:
    image: postgres
    environment:
      - POSTGRES_USER=attendize
      - POSTGRES_PASSWORD=attendize
      - POSTGRES_DB=attendize
    ports:
      - "5433:5432"
    volumes:
      - ./docker/pgdata:/var/lib/postgresql/data
    networks:
    - attendizenet
  maildev:
    image: djfarrelly/maildev
    ports:
      - "1080:80"
    networks:
      - attendizenet
  redis:
    image: redis
    networks:
      - attendizenet

networks:
  attendizenet:
    driver: bridge

A: The problem is that the PHP version provided by your Docker image, 7.0.7, is less than what is required by one or more of your dependencies defined in composer.json.
To fix the problem, you have multiple options:

*

*remove the dependencies (nah)

*use a base image that provides at least 7.0.8, see https://hub.docker.com/_/php/
It would be helpful if you shared your Dockerfile.

A: Maybe it will just suffice, to drop and prune the composer/composer image and container. And then to build it again.
It seems there is more uptodate version of PHP 7.0.x available. And this alone would satisfy the platform dependency mismatch..

*

*https://hub.docker.com/r/library/composer/

*https://github.com/composer/docker
..or you can try running the install like this:
$ composer install --ignore-platform-reqs

*

*this would ignore the mismatch and procede with the installation. Which may or may not be sufficient for development. I would not recommend ignoring the requirements at production (unless you really know what are you doing) though..


text:
Q: Epsilon delta proof min http://www.milefoot.com/math/calculus/limits/DeltaEpsilonProofs03.htm
I've been studying these épsilon delta proofs. In the non-linear case, he gets:
$$\delta=\min\left\{5-\sqrt{25-\dfrac{\epsilon}{3}},-5+\sqrt{25+\dfrac{\epsilon}{3}}\right\}$$
Well, I know that these $\delta$ are not equal the opposite of the other, but it has shown that $x$ must be within the range covered by these two deltas. Well, I already have bounded the $x-a$ (in this case, $x-5$) in therms of $\epsilon$, so it should work that for any given $\epsilon$, i could get only the  $-5+\sqrt{25+\dfrac{\epsilon}{3}}$. Why I have to get the minimum?

A: It is because $\delta$ has to be acceptable in the worst case.  Say we are proving $\lim_{x \to 0} f(x)=L$ and for (the given) $\epsilon$ we are within $\epsilon$ over the interval $\delta \in (-1,0.1)$  The definition of limit is symmetric:  it says whenever $x$ is within $\delta$ of $0$, then $|f(x)-L|\lt \epsilon$ so we have to shrink the interval to make it symmetric, so our answer should be within $\delta \in (-0.1,0.1)$.  This sounds restrictive, but it is not.  One can prove that symmetric limits leads to the same thing as asymmetric limits and every interval includes a symmetric interval.

A: He takes the minimum so that he can use the following two inequalities.
$$
\delta \leq 5-\sqrt{25-\dfrac{\epsilon}{3}} \\
\delta \leq -5+\sqrt{25+\dfrac{\epsilon}{3}}
$$
The first inequality above can be written as
$$
-5 + \sqrt{25-\dfrac{\epsilon}{3}} \leq -\delta.
$$
So the proof uses these inequalities to get
$$
-5 + \sqrt{25-\dfrac{\epsilon}{3}} \leq -\delta < x - 5 < \delta \leq -5+\sqrt{25+\dfrac{\epsilon}{3}}
$$
which is the inequality he intended to get (as you can see when he worked backwards). Hopefully that clears up why he needed to take $\delta$ as the minimum of the two quantities.


text:
Q: Wordpress check if you're on the current page (not menu) I am creating a little shortcode that acts like the custom menu widget, but I'm choosing the pages from a dropdown list, instead of creating a menus inside the wordpress (I'm also adding a color to it, so I can't just use regular wordpress menus widget).
So far so good, it's just one thing that's bothering me. I want to check if the page I'm on matches the one in my list (on the real page). I googled and searched a bit and found that with
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

I can get the current page I'm on (the link I see in my browser). Perfect!
So if I want to add a class called current page, all I need to see if my $actual_link matches with my selected link from the dropdown list.
I'm working this within a page bulder plugin The Creator, so I know how to create a working shortcode in it. My pages dropdown is created by making an array that will have page url as key and page name as a value. My loop is:
$args = array (
    'post_type' => 'page',
    'posts_per_page' => -1,
    'orderby' => 'menu_order',
    'order' => 'ASC',
);
$pages = get_posts($args);

$forms = array();
if(is_array($pages)){
    foreach ($pages as $page) {
        $forms[$page->url] = $page->post_title;
    }
}

And it works perfectly. Except that the url I get from this is of the form:
http://www.example.com/?page_id=150

Whereas I set my permalinks to be nice so the actual link in my browser is
http://www.example.com/my_page_name

The id is correct, and if I click on my 'menu' link I'll get to that page (desired result). But now I cannot just go and say:
$current = ($actual_link == $link) ? 'current_page' : '';

where $link is the variable that holds the link to the page from the dropdown, so that I can append this to my list to check if I'm on the current page (adds a current_page class). I need this class for the styling purposes - if I'm on the page that has this menu shortcode, next to the link that matches this page I'll get chevron (>).
So my question is, how to get the matching urls, no matter what permalink setting I use? Is there a way to specify this in the get_posts() query, or with the $_SERVER[] variable?
I am trying to avoid javascript with this one, and do everything server side.

A: You need to place get_the_ID() inside get_permalink() it will return the link which you have to match with $actual_link
$link = get_permalink(get_the_ID());

something like this.

A: Ok, found the answer.
I changed my query to
$args = array (
    'post_type' => 'page',
    'posts_per_page' => -1,
    'orderby' => 'menu_order',
    'order' => 'ASC',
);
$pages = get_posts($args);

$forms = array();
if(is_array($pages)){
    foreach ($pages as $page) {
        $forms[$page->ID] = $page->post_title;
    }
}

So that I can get page ID, then use
$link_out = get_permalink($link);

$current = ($actual_link == $link_out) ? 'current_page' : '';

And it works! :D


text:
Q: asp.net validation with validation group calling Page_ClientValidate not working as expected Hi I am calling the following javascript when user clicks complete button which is to call validation on all of the validation groups which i have 3.
but what is happening is that only the validation summary for the Photos one is being displayed when the others should also be showing. Can anyone help?
function EnsureValidation() {
        Page_ClientValidate('PropertyInformation');
        Page_ClientValidate('MarketCondition');
        Page_ClientValidate('Photos');
}

A: See Page_ClientValidate() with multiple ValidationGroups - how to show multiple summaries simultaneously?
Edit
Can't you just call Page_ClientValidate() (without any arguments) to validate all controls on the page?

A: I know this is an old post, The issue with using only Page_ClientValidate() is that, if you want to validate one group at a time, it won't work as it fires all the validation groups, you can do something like this,
function something(){
  if(Page_ClientValidate('Save'))
  {
     //Your Code
  }
  else if (Page_ClientValidate('Group2'))
  {
     //your code
  }
  else
  {
     //your code
  }
};


text:
Q: How do I add custom attributes to javascript tags in Wordpress? I am looking to enable CloudFlare's RocketLoader feature that enables asynchronous loading of Javascript for my Wordpress site. The problem, however, is that there is one plugin for  that I want to be loaded normally.
From a technical point of view, according to https://www.cloudflare.com/wiki/Rocket_Loader, I simply need to change any script tag I want ignored to have the data-cfasync="false" attribute as follows: <script data-cfasync="false" src="/javascript.js"></script>
Unfortunately, I can't seem to figure out how to do this for plugins that are automatically loaded by Wordpress.
Any ideas?

A: The following solution assumes that your plugins are using wp_enqueue_script() to insert scripts into the HTML code. If they don't they are broken by design and we cannot change the script tag.
This code works like the one in this answer, in fact, it is almost a duplicate …
First make two lists of all script URIs you want be ignored or not ignored by the rocket loader script. Then fill the $optimize and the $ignore arrays in the following script with these URIs.
function rocket_loader_attributes( $url )
{
    $optimize = array (
        'http://example.com/nr1.js',
        'http://example.com/nr2.js'
    );
    $ignore = array (
        'http://example.com/nr3.js',
        'http://example.com/nr4.js'
    );

    if ( in_array( $url, $optimize ) )
    { // this will be optimized
        return "$url' data-cfasync='true";
    }

    if ( in_array( $url, $ignore ) )
    { // this will be ignored
        return "$url' data-cfasync='false";
    }

    return $url;
}
add_filter( 'clean_url', 'rocket_loader_attributes', 11, 1 );

You can create a plugin with this code or – second best option – add it to your theme's functions.php.


text:
Q: Why is "extremely longer" not correct (according to the ACT)? The sentence that included the question was:

*

*
In addition, LEDs last far longer than standard bulbs.

Question: Which of the following alternatives to the bolded portion would NOT be acceptable?
  F. considerably
  G. a great deal
  H. extremely
  J. much
Answer: H

"Extremely" is an adverb (and not materially different in definition from the other answers available) and should be able to modify the adjective "longer", correct? I don't have an answer explanation, so it's unclear why they chose this. Can someone please explain why this is the answer? Thanks!

A: Extremely simply means very, and neither extremely nor very are used with comparatives, probably because English. I am sure no one would say *LEDs last very longer than standard bulbs.

Note that the modifier very cannot be used with comparatives.

*

*She is much older than her husband. (NOT *She is very older than her husband.) (English Practice)

You can use very much to intensify comparatives, but not very on its own:

We use very much not very to add emphasis to comparative adverbs and adjectives:

*

*Omah is very much better than Ian at basketball.
Not: Omah is very better than Ian …

*London is very much bigger than Naples.
Not: London is very bigger than Naples. (Cambridge)

Now, if your next question is, Can we say extremely much longer, then?, I wouldn't go there... :-)
CaGEl records the same restriction in use of very:

Non-comparatives like young allow very, while comparative younger does not: it takes
much, or (with submodification) very much, modifiers which are for the most part
inadmissible with non-comparatives:

*

*very/ *much young

*much /*very younger (p. 548)

Quirk (A Comprehensive Grammar of the English Language) also records

the restriction on premodification of adjectives and adverbs in the
absolute and comparative degrees with very (see pp. 472-473).

So there you go. With extremely, it should be

In addition, LEDs last extremely long [not extremely longer than standard bulbs] .

A: As Mr. William Strunk, Jr., said in 1918 in The Elements of Style, "Omit needless words."
If you were to say "In addition, LEDs last extremely longer than standard light bulbs," as you should not use the adverb "extremely" to modify the adjective "longer."
The British Council says (see link): "We use adverbs to give more information about the verb."
But perhaps the single best argument against saying "extremely longer" is that it elucidates nothing. "Far longer" elucidates even less. Why not merely say the LEDs last longer? To know how much longer LEDs last compared to conventional light bulbs, we have to first know how long conventional light bulbs last.
I think the ACT question is unhelpful at best and possibly extremely unfair.


text:
Q: pywin32 and pyttsx error, trouble combining the two i have pywin32 in my site packages and my pyttsx is in a separate folder. Is this the reason why i am getting the following error?
import win32api, sys, os
ImportError: DLL load failed: The specified module could not be found

The code is as follows,
import pyttsx
def onStart(name):
    print 'starting', name
def onWord(name, location, length):
    print 'word', name, location, length
def onEnd(name, completed):
    print 'finishing', name, completed
engine = pyttsx.init()
engine.connect('started-utterance', onStart)
engine.connect('started-word', onWord)
engine.connect('finished-utterance', onEnd)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

from here, http://pyttsx.readthedocs.org/en/latest/engine.html#examples
My pywin32 is from here,
http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/
for Py 2.7

A: The problem was that the file
pywintypes27.dll

was not in the right directory. It had to be in
'C:\Windows\System32'

@CristiFati

A: Use the pyttsx3 module instead . It supports both python3 and python2.
To install:
pip install pyttsx3.
It automatically installs those win32 and other dependencies.


text:
Q: Implementing chat layout with UICollectionView with AutoLayout Is what I'm trying to accomplish here even possible? I've been searching for hours for sample code and/or SO answers that demonstrate this simply enough to follow, but so far no luck.
Goal: implement something that looks roughly like this mock:

Yes, I know this is easy with a tableview, but the full design includes custom interactions, multiple columns, UIKit dynamics, and custom animations when adding/deleting cells, so UICollectionView is the better candidate. Until I can get this core layout to work, though, the rest of it is just a pipe dream.
So far I've started with a subclass of UICollectionViewCell that has a single label with constraints to all 4 sides of the content view. At which point I run into these issues:

*

*It's unclear how I can calculate collectionViewContentSize() when the cells don't exist yet, esp. given that the majority of cells are actually offscreen most of the time!

*If I just throw in an arbitrary content size (e.g., 320x1000), my views show up, but their heights don't adjust to the label content…I can't seem to read the cell height from within my UICollectionViewLayout subclass.

Seen or done anything like this? I'd include code, but after hours of futzing with it. I'm just looking for a clearer tutorial or sample code that fits this scenario.

A: There's a project you might want to look at. It's fairly involved and probably has a lot of code for situations that don't quite match yours, but does indeed create a chat view using a UICollectionView.
It can be found here:
https://github.com/jessesquires/JSQMessagesViewController
For item 1 - with regards to calculating collectionViewContentSize, I think you'll find you may not need to calculate that, at least as long as you're using a UICollectionViewFlowLayout subclass for the layout.
And for item 2 - rather than set a fixed 320x1000 take a look at the JSQMessagesCollectionViewFlowLayout.m for sizeItemAtIndexPath.
Sorry, this probably should have been a comment, but I lack the reputation to comment & so I made it an answer (doesn't that seem backwards? Ah well.)


text:
Q: perl oneliner : to match a pattern and substitute part of the matched pattern how to match a pattern which is as follows
input:  0xabcdxx 0xdefxxcf 0x12345xad
output: 0xabcd00 0xdef00cf 0x123450ad

I want the x to be replaced by 0 but the initial 0x at the start of a word should remain the same. Can a perl/sed oneliner is possible to get this way?
Thanks, in advance

A: With sed:
echo "0xabcdxx 0xdefxxcf 0x12345xad" | sed 's/\b0x/Y/g; s/x/0/g; s/Y/0x/g'

First substitute the 0x patterns at the word beginnings with a distinguishable pattern (I used 'Y'). Then replace all x with 0 and replace Y back with 0x.

A: $ echo '0xabcdxx 0xdefxxcf 0x12345xad' |
   perl -pe's/(?<!^0)(?<!\s0)x/0/g'
0xabcd00 0xdef00cf 0x123450ad

Maybe a teeny bit faster:
$ echo '0xabcdxx 0xdefxxcf 0x12345xad' |
   perl -pe's/x(?<!^0x)(?<!\s0x)/0/g'
0xabcd00 0xdef00cf 0x123450ad


text:
Q: Is it possible to change an app icon depending on the market? I have an app published in the U.S and in several countries, including Japan. I'd like to change the icon in Japan. I couldn't find anything on iTunes related to this issue.
Is this possible?
Thanks!

A: You cannot have different icons for the same app.
You will need to release two versions of your app - one in the Japanese store and one for all other territories.